package com.android.formula.database;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.android.formula.utils.Constants;

public class NoteDatabaseConnection {

	protected static final String TAG = "DataAdapter";

	Context mContext;

	SQLiteDatabase mDb;

	DatabaseHelper mDbHelper;

	public NoteDatabaseConnection(Context context) {
		this.mContext = context;
		mDbHelper = new DatabaseHelper(mContext, Constants.DB_NOTE);
	}

	public NoteDatabaseConnection createDatabase() throws SQLException {
		try {
			if (!checkDataBase()) {
				mDbHelper.createDataBase();
			}
		} catch (IOException mIOException) {
			Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
			throw new Error("UnableToCreateDatabase");
		}
		return this;
	}

	private boolean checkDataBase() {
		File dbFile = new File(DatabaseHelper.DB_PATH + Constants.DB_NOTE);
		return dbFile.exists();
	}

	public NoteDatabaseConnection open() throws SQLException {
		try {
			mDbHelper.openDataBase();
			mDbHelper.close();
			mDb = mDbHelper.getReadableDatabase();
		} catch (SQLException mSQLException) {
			Log.e(TAG, "open >>" + mSQLException.toString());
			throw mSQLException;
		}
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public final SQLiteDatabase getDatabase(){
	    return mDb;
	}
}
